import { request, useModel } from 'umi';
import { useState, useEffect } from 'react';
import getApiData from '@/services/cpasRequest';
import Popup from 'devextreme-react/popup';
import Button from 'devextreme-react/button';
import { DataGrid, SearchPanel, Column } from 'devextreme-react/data-grid';
import { intl, rTime } from '@/utils';

import ScrollView from 'devextreme-react/scroll-view';
import notify from 'devextreme/ui/notify';

export const AttachPopUp = (props: {
  visible: boolean;
  title: string;
  dgid: string;
  setAttachPopUpProps: (props: any) => void;
}) => {
  const { initialState } = useModel('@@initialState');
  const { dbname } = initialState?.curPart as API.CurPart;
  const { username, usercode } = initialState?.curUser as API.CurUser;
  const [attachList, setAttachList] = useState<any[]>([]);
  const [selectedList, setSelectedList] = useState<any[]>([]);
  async function attachListRefresh() {
    const list = await getAttachList(dbname);
    list.forEach((item: any) => {
      item.fullName = item.fjName + item.fjlx;
    });
    setAttachList(list);
  }
  const closePopup = () => {
    // runtime有问题，后面修改
    console.log(props.setAttachPopUpProps);
    props.setAttachPopUpProps({
      visible: false,
      title: '',
      dgid: '',
    });
  };

  async function handleAddAttach() {
    const res = await request('/cpasApi/draftFjManage/mountFjToDg', {
      method: 'post',
      data: {
        dgid: props.dgid,
        fjids: selectedList.map((item: any) => item.fjid),
        user: username,
        sjxmbh: dbname,
        dbname: dbname
      },
    });
    if (res.ok) {
      attachListRefresh();
      notify('添加成功', 'success', 1000);
    } else {
      notify('添加失败', 'error', 1000);
    }
    closePopup();
  }

  useEffect(() => {
    attachListRefresh();
  }, [props.title]);

  return (
    <>
      <Popup visible={props.visible} title={props.title} resizeEnabled={true} onHiding={closePopup}>
        <ScrollView height={'80%'}>
          <DataGrid
            className='PaperDevSortableGrid devHeadersCenter'
            dataSource={attachList}
            keyExpr="fjid"
            // focusedRowEnabled={true}
            hoverStateEnabled={true}
            showBorders={true}
            showColumnLines={false}
            allowColumnResizing={true}
            columnChooser={{ enabled: true }}
            columnFixing={{ enabled: true }}
            searchPanel={{
              visible: true,
              width: 230,
              placeholder: 'Search....',
            }}
            selection={{
              mode: 'multiple',
              selectAllMode: 'allPages',
              showCheckBoxesMode: 'onClick',
            }}
            onSelectionChanged={(e: any) => {
              setSelectedList(e.selectedRowsData);
            }}
            loadPanel={{ enabled: true }}
            // onContextMenuPreparing={dataMenuItems}
            toolbar={{
              items: [
                {
                  name: 'searchPanel',
                  location: 'after',
                },
              ],
            }}
          >
            <SearchPanel visible={true} />
            <Column
              dataField="fjsyh"
              caption={intl('audit.attach.fjsyh', '附件索引号')}
              width="100px"
            ></Column>
            <Column dataField="fullName" caption={intl('audit.attach.fjName', '附件名称')}></Column>
            <Column
              dataField="UserName"
              caption={intl('audit.attach.UserName', '用户名')}
              width="76px"
            ></Column>
            <Column
              dataField="LastEditDate"
              caption={intl('audit.attach.LastEditDate', '上次修改时间')}
              width="200px"
              customizeText={(item: any) => {
                return rTime(item.value)
              }}
            ></Column>
            <Column
              dataField="fjSize"
              caption={intl('audit.attach.fjSize', '附件大小')}
              width="76px"
            ></Column>
            <Column
              dataField="AddDate"
              caption={intl('audit.attach.AddDate', '添加日期')}
              width="200px"
              customizeText={(item: any) => {
                return rTime(item.value)
              }}
            ></Column>
          </DataGrid>
        </ScrollView>
        <Button
          style={{ marginRight: '10px' }}
          text={intl('paper.confirm', '确定')}
          onClick={handleAddAttach}
        />
        <Button text={intl('paper.cancel', '取消')} onClick={closePopup} />
      </Popup>
    </>
  );
};

async function getAttachList(dbname: string) {
  const res = await getApiData('dgfj.list', { dbname: dbname });
  if (res.ok) {
    // for (let i = 0; i < res.data.length; i++) {
    //   res.data[i]['LastEditDate'].replace(/T/, ' ');
    //   res.data[i]['LastEditDate'].replace(/\.[0-9]{3}Z/, '');
    //   res.data[i]['AddDate'].replace(/T/, ' ');
    //   res.data[i]['AddDate'].replace(/\.[0-9]{3}Z/, '');
    // }
    return res.data;
  } else {
    return [];
  }
}

export default AttachPopUp;
